#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
VMware虚拟机开机自启动脚本
功能：自动启动指定的VMware虚拟机
"""

import os
import subprocess
import sys
import time
from pathlib import Path

def log_message(message):
    """记录消息到控制台"""
    timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
    print(f"[{timestamp}] {message}")

def get_vmware_paths():
    """获取VMware可能的安装路径"""
    possible_paths = [
        "C:\\Program Files (x86)\\VMware\\VMware Workstation\\vmware.exe",
        "C:\\Program Files\\VMware\\VMware Workstation\\vmware.exe",
        "C:\\Program Files (x86)\\VMware\\VMware Workstation\\vmrun.exe",
        "C:\\Program Files\\VMware\\VMware Workstation\\vmrun.exe"
    ]
    
    valid_paths = {}
    for path in possible_paths:
        if os.path.exists(path):
            if "vmware.exe" in path:
                valid_paths["vmware"] = path
            elif "vmrun.exe" in path:
                valid_paths["vmrun"] = path
    
    return valid_paths

def start_virtual_machine(vmware_paths, vm_path, max_retries=10, retry_delay=30):
    """启动虚拟机，直到成功为止"""
    log_message(f"正在尝试启动虚拟机: {vm_path}")
    
    retry_count = 0
    
    while retry_count < max_retries:
        retry_count += 1
        log_message(f"第 {retry_count} 次尝试启动虚拟机...")
        
        # 首先尝试使用vmware.exe
        if "vmware" in vmware_paths:
            try:
                log_message(f"使用vmware.exe启动: {vmware_paths['vmware']}")
                process = subprocess.Popen(
                    [vmware_paths["vmware"], "-x", vm_path],
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE,
                    text=True
                )
                
                # 等待一下检查进程是否正常启动
                time.sleep(5)
                
                # 检查进程是否还在运行
                if process.poll() is None:
                    log_message("虚拟机启动命令已执行，进程正在运行")
                    return True
                else:
                    stdout, stderr = process.communicate()
                    log_message(f"vmware.exe进程已退出，返回码: {process.returncode}")
                    if stderr:
                        log_message(f"错误信息: {stderr}")
                        
            except Exception as e:
                log_message(f"使用vmware.exe启动失败: {str(e)}")
        
        # 如果vmware.exe失败或不存在，尝试使用vmrun.exe
        if "vmrun" in vmware_paths:
            try:
                log_message(f"使用vmrun.exe启动: {vmware_paths['vmrun']}")
                process = subprocess.Popen(
                    [vmware_paths["vmrun"], "start", vm_path],
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE,
                    text=True
                )
                
                # 等待一下检查进程是否正常启动
                time.sleep(5)
                
                # 检查进程是否还在运行
                if process.poll() is None:
                    log_message("虚拟机启动命令已执行，进程正在运行")
                    return True
                else:
                    stdout, stderr = process.communicate()
                    log_message(f"vmrun.exe进程已退出，返回码: {process.returncode}")
                    if stderr:
                        log_message(f"错误信息: {stderr}")
                        
            except Exception as e:
                log_message(f"使用vmrun.exe启动失败: {str(e)}")
        
        # 如果所有方法都失败了，等待后重试
        if retry_count < max_retries:
            log_message(f"启动失败，等待 {retry_delay} 秒后重试...")
            time.sleep(retry_delay)
        else:
            log_message(f"已达到最大重试次数 ({max_retries})，启动失败")
    
    return False

def add_to_startup():
    """将脚本添加到Windows开机启动项"""
    script_path = os.path.abspath(sys.argv[0])
    startup_folder = os.path.join(os.environ['APPDATA'], 
                                  'Microsoft', 
                                  'Windows', 
                                  'Start Menu', 
                                  'Programs', 
                                  'Startup')
    
    # 创建快捷方式
    shortcut_path = os.path.join(startup_folder, 'StartUbuntuVM.lnk')
    
    try:
        # 使用PowerShell创建快捷方式
        powershell_command = f'''
        $WScriptShell = New-Object -ComObject WScript.Shell
        $Shortcut = $WScriptShell.CreateShortcut('{shortcut_path}')
        $Shortcut.TargetPath = 'pythonw.exe'
        $Shortcut.Arguments = '{script_path}'
        $Shortcut.WorkingDirectory = '{os.path.dirname(script_path)}'
        $Shortcut.WindowStyle = 7
        $Shortcut.Save()
        '''
        
        subprocess.run([
            'powershell', 
            '-ExecutionPolicy', 
            'Bypass', 
            '-Command', 
            powershell_command
        ], check=True)
        
        log_message(f"已添加到开机启动项: {shortcut_path}")
        return True
    except Exception as e:
        log_message(f"添加到开机启动项失败: {str(e)}")
        return False

def main():
    """主函数"""
    log_message("===== VMware虚拟机自启动脚本开始执行 =====")
    
    # 虚拟机配置文件路径
    vm_path = "C:\\Users\\harry_shen\\Documents\\Virtual Machines\\home-assistant\\home-assistant.vmx"
    
    # 检查虚拟机文件是否存在
    if not os.path.exists(vm_path):
        log_message(f"错误: 找不到虚拟机文件 - {vm_path}")
        return 1
    
    # 获取VMware安装路径
    vmware_paths = get_vmware_paths()
    if not vmware_paths:
        log_message("错误: 未找到VMware安装路径")
        return 1
    
    # 启动虚拟机（带重试机制）
    log_message("开始启动虚拟机，将重试直到成功...")
    if start_virtual_machine(vmware_paths, vm_path, max_retries=10, retry_delay=30):
        log_message("✓ 虚拟机启动成功！Home Assistant正在启动中...")
    else:
        log_message("✗ 错误: 虚拟机启动失败，已达到最大重试次数")
        return 1
    
    # 添加到开机启动项
    add_to_startup()
    
    log_message("===== VMware虚拟机自启动脚本执行完成 =====")
    return 0

if __name__ == "__main__":
    sys.exit(main())